<template>
  <el-upload
      style="width: 100%;"
      ref="uploadRef"
      :show-file-list="false"
      :before-upload="beforeUpload"
      drag
      :on-success="handleSuccess"
      action="/filmAPI/file">
    <el-image v-if="img" :src="img" :lazy="true" style="height: 150px" fit="contain"></el-image>
    <div v-else>
      <el-icon class="el-icon--upload">
        <upload-filled></upload-filled>
      </el-icon>
      <div class="el-upload__text">
        <i style="font-size: 10px">点击上传或将图片拖拽于此</i>
      </div>
    </div>
  </el-upload>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {ElMessage, UploadInstance, UploadProps} from "element-plus";


const uploadRef = ref<UploadInstance>()
const props = defineProps({
  img: {     //内容
    type: String,
    default: "",
  },
});
const emits = defineEmits(["update:img"]);

onMounted(() => {

})
const beforeUpload: UploadProps['beforeUpload'] = (rawFile: { type: string; size: number;name:string }) => {
  if (!(rawFile.type === 'image/jpeg' || rawFile.type === "image/png")) {
    ElMessage.error('图片仅支持为jpg或png格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小需小于等于2MB!')
    return false
  }
  return true
}

const handleSuccess: UploadProps['onSuccess'] = (response) => {
  emits("update:img", '/filmAPI' + response);
}


</script>

<style scoped>
:deep(.el-upload-dragger) {
  padding: 0;
}
</style>